<?php

namespace App\Domains;

use App\Utils\FunctionUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

/**
 * 管理员domain
 */
class UserDomain
{
  private array $result = [
    'status' => 0,
    'message' => "success",
    'data' => [],
  ];

  /**
   * 会员添加
   * @param array $memberData
   * @return array
   */
  public function addMember(array $memberData): array
  {
    try {
      //主表
      $userId = DB::table('user')->insertGetId([
        'username' => $memberData['username'],
        'password' => Hash::make($memberData['password']),
        'phone' => $memberData['phone'] ?? '',
        'status' => 1,
        'createTime' => date("Y-m-d H:i:s"),
        'lastLoginTime' => date("Y-m-d H:i:s"),
        'groupId' => 0,
        'openid' => $memberData['openid'] ?? '',
        'openidDing' => $memberData['openidDing'] ?? '',
        'module' => $memberData['module'] ?? ''
      ]);
      //添加模块会员
      DB::table($memberData['module'] . '_user')->insert([
        'userId' => $userId,
        'realname' => $memberData['realname'] ?? '',
      ]);

      $this->result['status'] = 1;
      $this->result['data']['userId'] = $userId;
    } catch (\Exception $exception) {
      $this->result['message'] = $exception->getMessage();
    }

    return $this->result;

  }

  /**
   * 生成唯一用户名
   * @param string $module
   * @return string
   */
  public function createUniqueUsername(string $module = 'ad'): string
  {
    $module = substr(strtolower($module), 0, 2);
    $str = FunctionUtil::numberTo36(microtime(true) * 1000);
    return $module . $str;
  }


}
